package GUI;

import util.User;
import util.DatabaseUtil;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * 社交面板，用于查看好友动态和发布动态
 */
public class SocialPanel extends JPanel {
    private User currentUser;
    private JTextArea postTextArea;
    private JPanel postsPanel;
    private JPanel friendsPanel;
    private JList<String> friendsList;
    private DefaultListModel<String> friendsListModel;
    private JButton addFriendButton;
    private JButton removeFriendButton;

    public SocialPanel(User user) {
        this.currentUser = user;

        // 设置布局
        setLayout(new BorderLayout(10, 10));
        setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        // 创建标题
        JLabel titleLabel = new JLabel("社交动态", JLabel.CENTER);
        titleLabel.setFont(new Font("等线", Font.BOLD, 18));
        add(titleLabel, BorderLayout.NORTH);

        // 创建主面板（分割面板）
        JSplitPane mainSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
        mainSplitPane.setDividerLocation(200);

        // 创建左侧好友面板
        createFriendsPanel();
        mainSplitPane.setLeftComponent(friendsPanel);

        // 创建右侧动态面板
        JSplitPane rightSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
        rightSplitPane.setDividerLocation(150);

        // 创建发布动态面板
        JPanel createPostPanel = createPostPanel();
        rightSplitPane.setTopComponent(createPostPanel);

        // 创建动态列表面板
        createPostsPanel();
        JScrollPane postsScrollPane = new JScrollPane(postsPanel);
        postsScrollPane.setBorder(BorderFactory.createTitledBorder("动态列表"));
        postsScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        rightSplitPane.setBottomComponent(postsScrollPane);

        mainSplitPane.setRightComponent(rightSplitPane);

        add(mainSplitPane, BorderLayout.CENTER);

        // 加载好友列表和动态
        loadFriends();
        loadPosts();
    }

    /**
     * 创建好友面板
     */
    private void createFriendsPanel() {
        friendsPanel = new JPanel(new BorderLayout(5, 5));
        friendsPanel.setBorder(BorderFactory.createTitledBorder("好友列表"));

        // 创建好友列表模型
        friendsListModel = new DefaultListModel<>();
        friendsList = new JList<>(friendsListModel);
        friendsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

        // 添加列表选择监听器
        friendsList.addListSelectionListener(e -> {
            if (!e.getValueIsAdjusting()) {
                loadSelectedFriendPosts();
                updateFriendButtonsState();
            }
        });

        // 添加右键菜单
        JPopupMenu popupMenu = new JPopupMenu();
        JMenuItem viewPostsItem = new JMenuItem("查看动态");
        JMenuItem removeFriendItem = new JMenuItem("删除好友");

        viewPostsItem.addActionListener(e -> loadSelectedFriendPosts());
        removeFriendItem.addActionListener(e -> removeFriend());

        popupMenu.add(viewPostsItem);
        popupMenu.add(removeFriendItem);

        friendsList.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getButton() == MouseEvent.BUTTON3) { // 右键点击
                    int index = friendsList.locationToIndex(e.getPoint());
                    friendsList.setSelectedIndex(index);
                    if (index >= 0) {
                        popupMenu.show(friendsList, e.getX(), e.getY());
                    }
                }
            }
        });

        JScrollPane scrollPane = new JScrollPane(friendsList);
        friendsPanel.add(scrollPane, BorderLayout.CENTER);

        // 创建好友管理按钮面板
        JPanel friendButtonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));

        addFriendButton = new JButton("添加好友");
        addFriendButton.addActionListener(e -> showAddFriendDialog());
        friendButtonPanel.add(addFriendButton);

        removeFriendButton = new JButton("删除好友");
        removeFriendButton.addActionListener(e -> removeFriend());
        removeFriendButton.setEnabled(false); // 初始状态禁用
        friendButtonPanel.add(removeFriendButton);

        friendsPanel.add(friendButtonPanel, BorderLayout.NORTH);

        // 创建切换按钮
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));

        JButton allPostsButton = new JButton("所有动态");
        allPostsButton.addActionListener(e -> loadPosts());
        buttonPanel.add(allPostsButton);

        JButton myPostsButton = new JButton("我的动态");
        myPostsButton.addActionListener(e -> loadUserPosts(currentUser.getId()));
        buttonPanel.add(myPostsButton);

        friendsPanel.add(buttonPanel, BorderLayout.SOUTH);
    }

    /**
     * 更新好友按钮状态
     */
    private void updateFriendButtonsState() {
        boolean hasFriendSelected = friendsList.getSelectedIndex() != -1;
        removeFriendButton.setEnabled(hasFriendSelected);
    }

    /**
     * 显示添加好友对话框
     */
    private void showAddFriendDialog() {
        JPanel panel = new JPanel(new BorderLayout(5, 5));
        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        JPanel inputPanel = new JPanel(new GridLayout(1, 2, 5, 5));
        JLabel usernameLabel = new JLabel("用户名: ");
        JTextField usernameField = new JTextField(15);
        inputPanel.add(usernameLabel);
        inputPanel.add(usernameField);

        panel.add(new JLabel("请输入要添加的好友用户名:"), BorderLayout.NORTH);
        panel.add(inputPanel, BorderLayout.CENTER);

        int result = JOptionPane.showConfirmDialog(
                this, panel, "添加好友",
                JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);

        if (result == JOptionPane.OK_OPTION) {
            String username = usernameField.getText().trim();
            if (!username.isEmpty()) {
                addFriend(username);
            }
        }
    }

    /**
     * 添加好友
     */
    private void addFriend(String username) {
        if (username.equals(currentUser.getUsername())) {
            JOptionPane.showMessageDialog(this, "不能添加自己为好友！", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;

        try {
            conn = DatabaseUtil.getConnection();

            // 查询用户是否存在
            String checkUserSql = "SELECT id FROM users WHERE username = ?";
            pstmt = conn.prepareStatement(checkUserSql);
            pstmt.setString(1, username);
            rs = pstmt.executeQuery();

            if (!rs.next()) {
                JOptionPane.showMessageDialog(this, "用户不存在！", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }

            int friendId = rs.getInt("id");

            // 检查是否已经是好友
            pstmt.close();
            rs.close();
            String checkFriendSql = "SELECT * FROM user_friends WHERE user_id = ? AND friend_id = ?";
            pstmt = conn.prepareStatement(checkFriendSql);
            pstmt.setInt(1, currentUser.getId());
            pstmt.setInt(2, friendId);
            rs = pstmt.executeQuery();

            if (rs.next()) {
                JOptionPane.showMessageDialog(this, "该用户已经是您的好友！", "提示", JOptionPane.INFORMATION_MESSAGE);
                return;
            }

            // 添加好友关系（双向）
            pstmt.close();
            String addFriendSql = "INSERT INTO user_friends (user_id, friend_id) VALUES (?, ?)";
            pstmt = conn.prepareStatement(addFriendSql);

            // 当前用户添加好友
            pstmt.setInt(1, currentUser.getId());
            pstmt.setInt(2, friendId);
            pstmt.executeUpdate();

            // 好友添加当前用户（双向好友关系）
            pstmt.setInt(1, friendId);
            pstmt.setInt(2, currentUser.getId());
            pstmt.executeUpdate();

            JOptionPane.showMessageDialog(this, "好友添加成功！", "成功", JOptionPane.INFORMATION_MESSAGE);
            loadFriends(); // 重新加载好友列表

        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "添加好友失败：" + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        } finally {
            DatabaseUtil.closeConnection(conn, pstmt, rs);
        }
    }

    /**
     * 删除好友
     */
    private void removeFriend() {
        int selectedIndex = friendsList.getSelectedIndex();
        if (selectedIndex == -1) {
            JOptionPane.showMessageDialog(this, "请先选择要删除的好友！", "提示", JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        String friendInfo = friendsListModel.getElementAt(selectedIndex);
        int friendId = Integer.parseInt(friendInfo.substring(1, friendInfo.indexOf("]")));
        String friendName = friendInfo.substring(friendInfo.indexOf("]") + 1, friendInfo.indexOf("("));

        int confirm = JOptionPane.showConfirmDialog(
                this,
                "确定要删除好友 " + friendName + " 吗？",
                "删除好友",
                JOptionPane.YES_NO_OPTION);

        if (confirm == JOptionPane.YES_OPTION) {
            Connection conn = null;
            PreparedStatement pstmt = null;

            try {
                conn = DatabaseUtil.getConnection();

                // 删除双向好友关系
                String sql = "DELETE FROM user_friends WHERE " +
                        "(user_id = ? AND friend_id = ?) OR " +
                        "(user_id = ? AND friend_id = ?)";

                pstmt = conn.prepareStatement(sql);
                pstmt.setInt(1, currentUser.getId());
                pstmt.setInt(2, friendId);
                pstmt.setInt(3, friendId);
                pstmt.setInt(4, currentUser.getId());

                int affected = pstmt.executeUpdate();

                if (affected > 0) {
                    JOptionPane.showMessageDialog(this, "好友删除成功！", "成功", JOptionPane.INFORMATION_MESSAGE);
                    loadFriends(); // 重新加载好友列表
                    loadPosts(); // 重新加载动态
                } else {
                    JOptionPane.showMessageDialog(this, "好友删除失败！", "错误", JOptionPane.ERROR_MESSAGE);
                }

            } catch (SQLException | ClassNotFoundException e) {
                e.printStackTrace();
                JOptionPane.showMessageDialog(this, "删除好友失败：" + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            } finally {
                DatabaseUtil.closeConnection(conn, pstmt, null);
            }
        }
    }

    /**
     * 创建发布动态面板
     */
    private JPanel createPostPanel() {
        JPanel panel = new JPanel(new BorderLayout(5, 5));
        panel.setBorder(BorderFactory.createTitledBorder("发布动态"));

        // 创建文本区域
        postTextArea = new JTextArea(5, 20);
        postTextArea.setLineWrap(true);
        postTextArea.setWrapStyleWord(true);
        JScrollPane scrollPane = new JScrollPane(postTextArea);
        panel.add(scrollPane, BorderLayout.CENTER);

        // 创建发布按钮
        JButton postButton = new JButton("发布");
        postButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                publishPost();
            }
        });

        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        buttonPanel.add(postButton);
        panel.add(buttonPanel, BorderLayout.SOUTH);

        return panel;
    }

    /**
     * 创建动态列表面板
     */
    private void createPostsPanel() {
        postsPanel = new JPanel();
        postsPanel.setLayout(new BoxLayout(postsPanel, BoxLayout.Y_AXIS));
        // 设置首选大小，确保面板有一个固定的高度
        postsPanel.setPreferredSize(new Dimension(0, 500));
    }

    /**
     * 加载好友列表
     */
    private void loadFriends() {
        friendsListModel.clear();

        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;

        try {
            conn = DatabaseUtil.getConnection();

            // 查询当前用户的好友
            String sql = "SELECT u.id, u.username, u.name FROM users u " +
                    "JOIN user_friends f ON u.id = f.friend_id " +
                    "WHERE f.user_id = ?";

            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, currentUser.getId());

            rs = pstmt.executeQuery();

            while (rs.next()) {
                int friendId = rs.getInt("id");
                String username = rs.getString("username");
                String name = rs.getString("name");

                // 将好友信息以"[ID]姓名(用户名)"的格式添加到列表
                friendsListModel.addElement("[" + friendId + "]" + name + "(" + username + ")");
            }
        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "加载好友列表失败：" + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        } finally {
            DatabaseUtil.closeConnection(conn, pstmt, rs);
        }

        // 更新按钮状态
        updateFriendButtonsState();
    }

    /**
     * 加载所有动态
     */
    public void loadPosts() {
        // 清除removeAll()，因为已经移到addPostsToPanel方法中
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;

        try {
            conn = DatabaseUtil.getConnection();

            // 查询所有动态，包括当前用户和好友的动态
            String sql = "SELECT p.id, p.user_id, p.content, p.posted_at, u.username, u.name " +
                    "FROM social_posts p " +
                    "JOIN users u ON p.user_id = u.id " +
                    "WHERE p.user_id = ? " + // 当前用户的动态
                    "OR p.user_id IN (SELECT friend_id FROM user_friends WHERE user_id = ?) " + // 好友的动态
                    "ORDER BY p.posted_at DESC";

            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, currentUser.getId());
            pstmt.setInt(2, currentUser.getId());

            rs = pstmt.executeQuery();

            addPostsToPanel(rs);
        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "加载动态失败：" + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        } finally {
            DatabaseUtil.closeConnection(conn, pstmt, rs);
        }
    }

    /**
     * 加载指定用户的动态
     */
    private void loadUserPosts(int userId) {
        // 清除removeAll()，因为已经移到addPostsToPanel方法中
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;

        try {
            conn = DatabaseUtil.getConnection();

            // 查询指定用户的动态
            String sql = "SELECT p.id, p.user_id, p.content, p.posted_at, u.username, u.name " +
                    "FROM social_posts p " +
                    "JOIN users u ON p.user_id = u.id " +
                    "WHERE p.user_id = ? " +
                    "ORDER BY p.posted_at DESC";

            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, userId);

            rs = pstmt.executeQuery();

            addPostsToPanel(rs);
        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "加载动态失败：" + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        } finally {
            DatabaseUtil.closeConnection(conn, pstmt, rs);
        }
    }

    /**
     * 加载所选好友的动态
     */
    private void loadSelectedFriendPosts() {
        int selectedIndex = friendsList.getSelectedIndex();
        if (selectedIndex != -1) {
            String friendInfo = friendsListModel.getElementAt(selectedIndex);
            // 从"[ID]姓名(用户名)"格式中提取ID
            int friendId = Integer.parseInt(friendInfo.substring(1, friendInfo.indexOf("]")));
            loadUserPosts(friendId);
        }
    }

    /**
     * 将ResultSet中的动态数据添加到面板
     */
    private void addPostsToPanel(ResultSet rs) throws SQLException {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");

        // 清空现有内容
        postsPanel.removeAll();

        while (rs.next()) {
            int postId = rs.getInt("id");
            int userId = rs.getInt("user_id");
            String content = rs.getString("content");
            Timestamp postedAt = rs.getTimestamp("posted_at");
            String username = rs.getString("username");
            String name = rs.getString("name");

            // 创建动态面板
            JPanel postPanel = new JPanel(new BorderLayout(5, 5));
            postPanel.setBorder(BorderFactory.createCompoundBorder(
                    BorderFactory.createMatteBorder(0, 0, 1, 0, Color.LIGHT_GRAY),
                    new EmptyBorder(10, 10, 10, 10)));

            // 设置最大宽度，确保动态面板宽度不超过父容器
            postPanel.setMaximumSize(new Dimension(Integer.MAX_VALUE, postPanel.getPreferredSize().height));

            // 创建用户信息和时间面板
            JPanel headerPanel = new JPanel(new BorderLayout());

            JLabel userLabel = new JLabel(name + " (" + username + ")");
            userLabel.setFont(new Font("等线", Font.BOLD, 14));
            headerPanel.add(userLabel, BorderLayout.WEST);

            JLabel timeLabel = new JLabel(dateFormat.format(postedAt));
            timeLabel.setForeground(Color.GRAY);
            headerPanel.add(timeLabel, BorderLayout.EAST);

            // 如果是当前用户的动态，添加删除按钮
            if (userId == currentUser.getId()) {
                JButton deleteButton = new JButton("删除");
                deleteButton.setFont(new Font("等线", Font.PLAIN, 12));
                deleteButton.setPreferredSize(new Dimension(60, 25));
                deleteButton.addActionListener(e -> deletePost(postId, postPanel));

                JPanel controlPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
                controlPanel.setOpaque(false);
                controlPanel.add(deleteButton);
                headerPanel.add(controlPanel, BorderLayout.EAST);
            }

            postPanel.add(headerPanel, BorderLayout.NORTH);

            // 创建内容面板
            JTextArea contentArea = new JTextArea(content);
            contentArea.setEditable(false);
            contentArea.setLineWrap(true);
            contentArea.setWrapStyleWord(true);
            contentArea.setBackground(new Color(245, 245, 245));
            contentArea.setBorder(new EmptyBorder(5, 5, 5, 5));

            postPanel.add(contentArea, BorderLayout.CENTER);

            // 创建底部面板，包含评论计数和操作按钮
            JPanel footerPanel = new JPanel(new BorderLayout(5, 5));
            footerPanel.setOpaque(false);

            // 获取评论数量
            int commentCount = getCommentCount(postId);
            JLabel commentCountLabel = new JLabel(commentCount + " 条评论");
            commentCountLabel.setForeground(new Color(100, 100, 100));
            footerPanel.add(commentCountLabel, BorderLayout.WEST);

            // 添加查看详情按钮
            JButton viewDetailButton = new JButton("查看详情");
            viewDetailButton.setFont(new Font("等线", Font.PLAIN, 12));
            viewDetailButton
                    .addActionListener(e -> showPostDetailDialog(postId, userId, name, username, content, postedAt));

            JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
            buttonPanel.setOpaque(false);
            buttonPanel.add(viewDetailButton);
            footerPanel.add(buttonPanel, BorderLayout.EAST);

            postPanel.add(footerPanel, BorderLayout.SOUTH);

            // 将动态面板添加到总面板
            postsPanel.add(postPanel);
            postsPanel.add(Box.createVerticalStrut(10)); // 添加间距
        }

        // 添加弹性填充，确保内容顶部对齐
        postsPanel.add(Box.createVerticalGlue());

        // 重新绘制面板
        postsPanel.revalidate();
        postsPanel.repaint();
    }

    /**
     * 获取动态评论数量
     */
    private int getCommentCount(int postId) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        int count = 0;

        try {
            conn = DatabaseUtil.getConnection();
            String sql = "SELECT COUNT(*) AS count FROM post_comments WHERE post_id = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, postId);
            rs = pstmt.executeQuery();

            if (rs.next()) {
                count = rs.getInt("count");
            }
        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            DatabaseUtil.closeConnection(conn, pstmt, rs);
        }

        return count;
    }

    /**
     * 显示动态详情对话框
     */
    private void showPostDetailDialog(int postId, int userId, String name, String username, String content,
            Timestamp postedAt) {
        // 创建对话框
        JDialog dialog = new JDialog();
        dialog.setTitle("动态详情");
        dialog.setSize(600, 500);
        dialog.setLocationRelativeTo(this);
        dialog.setModal(true);

        // 创建内容面板
        JPanel contentPanel = new JPanel(new BorderLayout(10, 10));
        contentPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));

        // 创建顶部面板 - 用户信息和时间
        JPanel headerPanel = new JPanel(new BorderLayout());
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        JLabel userLabel = new JLabel(name + " (" + username + ")");
        userLabel.setFont(new Font("等线", Font.BOLD, 16));
        headerPanel.add(userLabel, BorderLayout.WEST);

        JLabel timeLabel = new JLabel(dateFormat.format(postedAt));
        timeLabel.setForeground(Color.GRAY);
        headerPanel.add(timeLabel, BorderLayout.EAST);

        contentPanel.add(headerPanel, BorderLayout.NORTH);

        // 创建动态内容面板
        JTextArea contentArea = new JTextArea(content);
        contentArea.setEditable(false);
        contentArea.setLineWrap(true);
        contentArea.setWrapStyleWord(true);
        contentArea.setBackground(new Color(250, 250, 250));
        contentArea.setFont(new Font("等线", Font.PLAIN, 14));
        contentArea.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        JScrollPane contentScrollPane = new JScrollPane(contentArea);
        contentScrollPane.setBorder(BorderFactory.createLineBorder(new Color(230, 230, 230)));
        contentScrollPane.setPreferredSize(new Dimension(570, 100));

        JPanel contentContainerPanel = new JPanel(new BorderLayout());
        contentContainerPanel.setBorder(BorderFactory.createEmptyBorder(10, 0, 10, 0));
        contentContainerPanel.add(contentScrollPane, BorderLayout.CENTER);

        contentPanel.add(contentContainerPanel, BorderLayout.CENTER);

        // 创建评论区面板
        JPanel commentsContainerPanel = new JPanel(new BorderLayout(5, 5));
        commentsContainerPanel.setBorder(BorderFactory.createTitledBorder("评论区"));

        // 创建评论列表面板
        JPanel commentsPanel = new JPanel();
        commentsPanel.setLayout(new BoxLayout(commentsPanel, BoxLayout.Y_AXIS));
        JScrollPane commentsScrollPane = new JScrollPane(commentsPanel);
        commentsScrollPane.setBorder(null);

        // 加载评论
        loadComments(commentsPanel, postId);

        commentsContainerPanel.add(commentsScrollPane, BorderLayout.CENTER);

        // 创建评论输入面板
        JPanel commentInputPanel = new JPanel(new BorderLayout(5, 5));
        commentInputPanel.setBorder(BorderFactory.createEmptyBorder(5, 0, 0, 0));

        JTextField commentField = new JTextField();
        commentInputPanel.add(commentField, BorderLayout.CENTER);

        JButton commentButton = new JButton("发表评论");
        commentButton.addActionListener(e -> {
            String commentText = commentField.getText().trim();
            if (!commentText.isEmpty()) {
                addComment(postId, commentText, commentsPanel);
                commentField.setText("");
                // 更新主界面中的评论计数
                dialog.dispose();
                loadPosts(); // 重新加载动态列表以更新评论计数
            }
        });
        commentInputPanel.add(commentButton, BorderLayout.EAST);

        commentsContainerPanel.add(commentInputPanel, BorderLayout.SOUTH);

        contentPanel.add(commentsContainerPanel, BorderLayout.SOUTH);

        dialog.setContentPane(contentPanel);
        dialog.setVisible(true);
    }

    /**
     * 删除动态
     */
    private void deletePost(int postId, JPanel postPanel) {
        int confirm = JOptionPane.showConfirmDialog(
                this,
                "确定要删除这条动态吗？相关评论也将被删除。",
                "删除动态",
                JOptionPane.YES_NO_OPTION);

        if (confirm == JOptionPane.YES_OPTION) {
            Connection conn = null;
            PreparedStatement pstmt = null;

            try {
                conn = DatabaseUtil.getConnection();
                conn.setAutoCommit(false); // 开始事务

                // 先删除动态的所有评论
                String deleteCommentsSql = "DELETE FROM post_comments WHERE post_id = ?";
                pstmt = conn.prepareStatement(deleteCommentsSql);
                pstmt.setInt(1, postId);
                pstmt.executeUpdate();

                // 再删除动态本身
                pstmt.close();
                String deletePostSql = "DELETE FROM social_posts WHERE id = ? AND user_id = ?";
                pstmt = conn.prepareStatement(deletePostSql);
                pstmt.setInt(1, postId);
                pstmt.setInt(2, currentUser.getId());

                int affected = pstmt.executeUpdate();

                if (affected > 0) {
                    conn.commit(); // 提交事务
                    postsPanel.remove(postPanel);
                    postsPanel.remove(postsPanel.getComponentCount() - 1); // 移除间距
                    postsPanel.revalidate();
                    postsPanel.repaint();
                    JOptionPane.showMessageDialog(this, "动态已成功删除！", "成功", JOptionPane.INFORMATION_MESSAGE);
                } else {
                    conn.rollback(); // 回滚事务
                    JOptionPane.showMessageDialog(this, "删除动态失败！", "错误", JOptionPane.ERROR_MESSAGE);
                }

            } catch (SQLException | ClassNotFoundException e) {
                e.printStackTrace();
                try {
                    if (conn != null) {
                        conn.rollback(); // 出错时回滚
                    }
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
                JOptionPane.showMessageDialog(this, "删除动态失败：" + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            } finally {
                try {
                    if (conn != null) {
                        conn.setAutoCommit(true); // 恢复自动提交
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                DatabaseUtil.closeConnection(conn, pstmt, null);
            }
        }
    }

    /**
     * 加载评论
     */
    private void loadComments(JPanel commentsPanel, int postId) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;

        try {
            conn = DatabaseUtil.getConnection();

            // 查询指定动态的评论
            String sql = "SELECT c.id, c.user_id, c.content, c.commented_at, u.name, u.username " +
                    "FROM post_comments c " +
                    "JOIN users u ON c.user_id = u.id " +
                    "WHERE c.post_id = ? " +
                    "ORDER BY c.commented_at ASC";

            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, postId);

            rs = pstmt.executeQuery();

            SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd HH:mm");

            while (rs.next()) {
                int commentId = rs.getInt("id");
                int userId = rs.getInt("user_id");
                String commentContent = rs.getString("content");
                Timestamp commentedAt = rs.getTimestamp("commented_at");
                String commenterName = rs.getString("name");
                String commenterUsername = rs.getString("username");

                // 创建评论面板
                JPanel commentPanel = new JPanel(new BorderLayout());
                commentPanel.setMaximumSize(new Dimension(Integer.MAX_VALUE, 50));

                // 创建评论内容标签
                JLabel commentLabel = new JLabel(
                        "<html><b>" + commenterName + "(" + commenterUsername + ")</b>: " +
                                commentContent +
                                " <font color='gray'><small>" + dateFormat.format(commentedAt)
                                + "</small></font></html>");
                commentLabel.setBorder(BorderFactory.createEmptyBorder(2, 0, 2, 0));
                commentPanel.add(commentLabel, BorderLayout.CENTER);

                // 如果是当前用户的评论，添加删除选项
                if (userId == currentUser.getId()) {
                    JButton deleteCommentButton = new JButton("删除");
                    deleteCommentButton.setFont(new Font("等线", Font.PLAIN, 10));
                    deleteCommentButton.setPreferredSize(new Dimension(50, 20));
                    deleteCommentButton.addActionListener(e -> deleteComment(commentId, postId, commentsPanel));

                    JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 0, 0));
                    buttonPanel.setOpaque(false);
                    buttonPanel.add(deleteCommentButton);

                    commentPanel.add(buttonPanel, BorderLayout.EAST);
                }

                commentsPanel.add(commentPanel);
            }
        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            DatabaseUtil.closeConnection(conn, pstmt, rs);
        }
    }

    /**
     * 删除评论
     */
    private void deleteComment(int commentId, int postId, JPanel commentsPanel) {
        Connection conn = null;
        PreparedStatement pstmt = null;

        try {
            conn = DatabaseUtil.getConnection();

            String sql = "DELETE FROM post_comments WHERE id = ? AND user_id = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, commentId);
            pstmt.setInt(2, currentUser.getId());

            int affected = pstmt.executeUpdate();

            if (affected > 0) {
                // 清空评论面板并重新加载评论
                commentsPanel.removeAll();
                loadComments(commentsPanel, postId);
                commentsPanel.revalidate();
                commentsPanel.repaint();
            } else {
                JOptionPane.showMessageDialog(this, "删除评论失败！", "错误", JOptionPane.ERROR_MESSAGE);
            }

        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "删除评论失败：" + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        } finally {
            DatabaseUtil.closeConnection(conn, pstmt, null);
        }
    }

    /**
     * 发布动态
     */
    private void publishPost() {
        String content = postTextArea.getText().trim();

        if (content.isEmpty()) {
            JOptionPane.showMessageDialog(this, "动态内容不能为空！", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        Connection conn = null;
        PreparedStatement pstmt = null;

        try {
            conn = DatabaseUtil.getConnection();

            // 插入动态
            String sql = "INSERT INTO social_posts (user_id, content) VALUES (?, ?)";

            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, currentUser.getId());
            pstmt.setString(2, content);

            int affectedRows = pstmt.executeUpdate();

            if (affectedRows > 0) {
                JOptionPane.showMessageDialog(this, "动态发布成功！", "成功", JOptionPane.INFORMATION_MESSAGE);
                postTextArea.setText(""); // 清空输入框
                loadPosts(); // 重新加载动态
            } else {
                JOptionPane.showMessageDialog(this, "动态发布失败！", "错误", JOptionPane.ERROR_MESSAGE);
            }
        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "动态发布失败：" + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        } finally {
            DatabaseUtil.closeConnection(conn, pstmt, null);
        }
    }

    /**
     * 添加评论
     */
    private void addComment(int postId, String content, JPanel commentsPanel) {
        if (content.trim().isEmpty()) {
            return;
        }

        Connection conn = null;
        PreparedStatement pstmt = null;

        try {
            conn = DatabaseUtil.getConnection();

            // 插入评论
            String sql = "INSERT INTO post_comments (post_id, user_id, content) VALUES (?, ?, ?)";

            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, postId);
            pstmt.setInt(2, currentUser.getId());
            pstmt.setString(3, content);

            int affectedRows = pstmt.executeUpdate();

            if (affectedRows > 0) {
                // 清空评论面板并重新加载评论
                commentsPanel.removeAll();
                loadComments(commentsPanel, postId);
                commentsPanel.revalidate();
                commentsPanel.repaint();
            }
        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "评论发布失败：" + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        } finally {
            DatabaseUtil.closeConnection(conn, pstmt, null);
        }
    }
}
